import { getLoginUser } from '@/api/userController'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('loginUser', () => {

  // 当前登录用户
  const loginUser = ref<API.LoginUserVO>({
    userName: '未登录'
  })

  // 记住密码相关状态
  const rememberedUsername = ref<string>('')
  const rememberedPassword = ref<string>('') // base64 编码后的密码
  const isRemember = ref<boolean>(false)

  // 获取当前登录用户
  const fetchLoginUser = async () => {
    try {
      const res = await getLoginUser();
      if (res.data?.code === 0 && res.data.data) {
        setLoginUser(res.data.data)
      }
    } catch (error) {
      console.error(error)
    }
  }

  // 设置当前登录用户
  const setLoginUser = (newLoginUser: API.LoginUserVO) => {
    loginUser.value = newLoginUser;
  }

  // 获取记住的用户信息（解码密码）
  const getRememberedInfo = () => {
    if (!isRemember.value) {
      return { username: '', password: '', isRemember: false }
    }

    let password = ''
    if (rememberedPassword.value) {
      try {
        password = decodeURIComponent(atob(rememberedPassword.value))
      } catch (error) {
        console.error('密码解码失败:', error)
        password = rememberedPassword.value // 兼容旧格式
      }
    }

    return {
      username: rememberedUsername.value,
      password: password,
      isRemember: isRemember.value
    }
  }

  // 保存记住的用户信息
  const saveRememberedInfo = (username: string, password: string, remember: boolean) => {
    if (remember) {
      // 使用 base64 编码存储密码
      rememberedUsername.value = username
      rememberedPassword.value = btoa(encodeURIComponent(password))
      isRemember.value = true
    } else {
      // 清除记住的信息
      clearRememberedInfo()
    }
  }

  // 清除记住的用户信息
  const clearRememberedInfo = () => {
    rememberedUsername.value = ''
    rememberedPassword.value = ''
    isRemember.value = false
  }

  // 返回
  return {
    loginUser,
    rememberedUsername,
    rememberedPassword,
    isRemember,
    fetchLoginUser,
    setLoginUser,
    getRememberedInfo,
    saveRememberedInfo,
    clearRememberedInfo
  }
}, {
  persist: {
    key: 'user-store'
  }
})
